package cn.genmer.test.security.config;


import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticSearchClient {
//    @Value("${spring.elasticsearch.rest.uris}")
//    private String hosts;
//    @Value("${spring.elasticsearch.rest.username}")
//    private String userName;
//    @Value("${spring.elasticsearch.rest.password}")
//    private String password;

//    @SuppressWarnings("deprecation")
//    @Bean(name="esClient")
    public static RestHighLevelClient getClient() {
//        String[] hosts = this.hosts.split(",");
        HttpHost[] httpHosts = new HttpHost[2];
        httpHosts[0] = new HttpHost("www.reentrantlock.cn", 9200, "http");
        httpHosts[1] = new HttpHost("www.reentrantlock.cn", 9201, "http");

//        for(int i=0;i<hosts.length;i++) {
//            httpHosts[i] = new HttpHost(hosts[i], 9200, "http");
//        }
        //设置密码
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "elastic"));

        //设置超时
        RestClientBuilder builder = RestClient.builder(httpHosts).setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
            @Override
            public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
                requestConfigBuilder.setConnectTimeout(-1);
                requestConfigBuilder.setSocketTimeout(-1);
                requestConfigBuilder.setConnectionRequestTimeout(-1);
                return requestConfigBuilder;
            }
        }).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
            @Override
            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                httpClientBuilder.disableAuthCaching();
                return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }
        });

        RestHighLevelClient client = new RestHighLevelClient(builder);
        return client;
    }
}